{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ffa328f9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from llama_index import (\n",
    "    SimpleDirectoryReader,\n",
    "    VectorStoreIndex,\n",
    "    download_loader,\n",
    "    RAKEKeywordTableIndex,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "54fa1547-3d32-46ea-9d75-6b167c1e97c3",
   "metadata": {},
   "source": [
    "Set service context to enable streaming"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3a003a97-874c-4807-b017-37270ea7a682",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from llama_index import LLMPredictor, ServiceContext\n",
    "from llama_index.llms import OpenAI\n",
    "\n",
    "service_context = ServiceContext.from_defaults(\n",
    "    llm=OpenAI(temperature=0, model=\"text-davinci-003\")\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "479d39ec-3def-438c-ae63-7fb7062ef74b",
   "metadata": {
    "tags": []
   },
   "source": [
    "Load document and build index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0ab64036-518b-488a-9bc5-888534c4bf50",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "reader = SimpleDirectoryReader(input_files=[\"../data/10k/lyft_2021.pdf\"])\n",
    "data = reader.load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "aa856570-ae8a-4fe6-8f7c-59a698308fdb",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "index = VectorStoreIndex.from_documents(data, service_context=service_context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "40133993-2413-444c-a2a3-796cf9e263f8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "query_engine = index.as_query_engine(streaming=True, similarity_top_k=3)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "11a91d5a-470a-4896-8a10-732f1e29643f",
   "metadata": {},
   "source": [
    "Stream response with page citation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a2d96a34-481c-4330-9618-8bae1aa087d6",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "• The ongoing COVID-19 pandemic continues to impact communities in the United States, Canada and globally (page 6). \n",
      "• The pandemic and related responses caused decreased demand for our platform leading to decreased revenues as well as decreased earning opportunities for drivers on our platform (page 6).\n",
      "• Our business continues to be impacted by the COVID-19 pandemic (page 6).\n",
      "• The exact timing and pace of the recovery remain uncertain (page 6).\n",
      "• The extent to which our operations will continue to be impacted by the pandemic will depend largely on future developments, which are highly uncertain and cannot be accurately predicted (page 6).\n",
      "• An increase in cases due to variants of the virus has caused many businesses to delay employees returning to the office (page 6).\n",
      "• We anticipate that continued social distancing, altered consumer behavior, reduced travel and commuting, and expected corporate cost cutting will be significant challenges for us (page 6).\n",
      "• We have adopted multiple measures, including, but not limited, to establishing new health and safety requirements for ridesharing and updating workplace policies (page 6).\n",
      "• We have had to take certain cost-cutting measures, including lay-offs, furloughs and salary reductions, which may have adversely affect employee morale, our culture and our ability to attract and retain employees (page 18).\n",
      "• The ultimate impact of the COVID-19 pandemic on our users, customers, employees, business, operations and financial performance depends on many factors that are not within our control (page 18)."
     ]
    }
   ],
   "source": [
    "response = query_engine.query(\n",
    "    \"What was the impact of COVID? Show statements in bullet form and show page reference after each statement.\"\n",
    ")\n",
    "response.print_response_stream()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "28251b19-ad4a-48e5-be85-2ec60b9e37e3",
   "metadata": {},
   "source": [
    "Inspect source nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "ea3a9505-23e7-482f-a516-87c3ccd3da70",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----\n",
      "Text:\t Impact of COVID-19 to our BusinessThe  ongoing  COVID-19  pandemic  continues  to  impact  communities  in  the  United  States,  Canada  and  globally.  Since  the  pandemic  began  in  March  2020,governments  and  private  businesses  -  at  the  recommendation  of  public  health  officials  -  have  enacted  precautions  to  mitigate  the  spread  of  the  virus,  including  travelrestrictions  and  social  distancing  measures  in  many  regions  of  the  United  States  and  Canada,  and  many  enterprises  have  instituted  and  maintained  work  from  homeprograms and limited  the number of employees on site. Beginning in the middle of March 2020, the pandemic and these related responses caused decreased demand for ourplatform  leading to decreased revenues as well as decreased earning opportunities for drivers on our platform. Our business continues to be impacted by the COVID-19pandemic. Although  we have seen some signs of demand improving, particularly compared to the dema ...\n",
      "Metadata:\t {'page_label': '6', 'file_name': 'lyft_2021.pdf'}\n",
      "Score:\t 0.821\n",
      "-----\n",
      "Text:\t will  continue  to  be  impacted  by  the  pandemic  will  depend  largely  on  future  developments,  which  are  highly  uncertain  and  cannot  beaccurately predicted,  including new information which may emerge concerning COVID-19 variants and the severity of the pandemic and actions by government authoritiesand  private businesses to contain the pandemic or recover from its impact, among other things. For example, an increase in cases due to variants of the virus has causedmany  businesses to delay employees returning to the office. Even as travel restrictions and shelter-in-place orders are modified or lifted, we anticipate that continued socialdistancing, altered consu mer behavior, reduced travel and commuting, and expected corporate cost cutting will be significant challenges for us. The strength and duration ofthese challenges cannot b e presently estimated.In  response to the COVID-19 pandemic, we have adopted multiple measures, including, but not limited, to establishing ne ...\n",
      "Metadata:\t {'page_label': '56', 'file_name': 'lyft_2021.pdf'}\n",
      "Score:\t 0.808\n",
      "-----\n",
      "Text:\t storing unrented and returned vehicles. These impacts to the demand for and operations of the different rental programs have and may continue to adversely affectour business, financial condi tion and results of operation.• The COVID-19 pandemic may delay or prevent us, or our current or prospective partners and suppliers, from being able to test, develop or deploy autonomousvehicle-related  technology,  including  through  direct  impacts  of  the  COVID-19  virus  on  employee  and  contractor  health;  reduced  consumer  demand  forautonomous vehicle  travel resulting from an overall reduced demand for travel; shelter-in-place orders by local, state or federal governments negatively impactingoperations,  including our ability to test autonomous vehicle-related technology; impacts to the supply chains of our current or prospective partners and suppliers;or  economic  impacts  limiting  our  or  our  current  or  prospective  partners’  or  suppliers’  ability  to  expend  resources  o ...\n",
      "Metadata:\t {'page_label': '18', 'file_name': 'lyft_2021.pdf'}\n",
      "Score:\t 0.805\n"
     ]
    }
   ],
   "source": [
    "for node in response.source_nodes:\n",
    "    print(\"-----\")\n",
    "    text_fmt = node.node.get_content().strip().replace(\"\\n\", \" \")[:1000]\n",
    "    print(f\"Text:\\t {text_fmt} ...\")\n",
    "    print(f\"Metadata:\\t {node.node.metadata}\")\n",
    "    print(f\"Score:\\t {node.score:.3f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "673aa070-cefe-4e1b-bc16-e2a64bbb5f67",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
